﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

namespace Ekton_Manage_Framework.Redis
{
    public static class HelpRedisFuncHash
    {
        public static HashEntry[] ToHashEntries(this object obj)
        {
            PropertyInfo[] properties = obj.GetType().GetProperties();
            return properties.Select(propertype =>
                                 new HashEntry(propertype.Name, propertype.GetValue(obj).ToString()))
                             .ToArray();
        }

        public static T ConvertFromRedis<T>(this HashEntry[] hashEntries)
        {
            PropertyInfo[] properties = typeof(T).GetProperties();
            var obj = Activator.CreateInstance(typeof(T));
            foreach (var property in properties)
            {
                HashEntry entry = hashEntries.FirstOrDefault(g => g.Name.ToString().Equals(property.Name));
                if (entry.Equals(new HashEntry())) { continue; }
                Match m = Regex.Match(Convert.ChangeType(entry.Value, property.PropertyType).ToString(), @"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$", RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    //可以转换 是Guid 不可直接将对象给到Guid,所以先转成Guid在给值
                    property.SetValue(obj, Guid.Parse(Convert.ChangeType(entry.Value, property.PropertyType).ToString()));
                }
                else
                {
                    //不可转换 
                    property.SetValue(obj, Convert.ChangeType(entry.Value.ToString(), property.PropertyType));
                }
            }
            return (T)obj;
        }
    }
}
